<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>生态圈系统-验证优惠券</title>
  <link rel="icon" th:href="@{/images/favicon.ico}" th:mce_href="@{/images/favicon.ico}" type="image/x-icon">
  <link rel="shortcut icon" th:href="@{/images/favicon.ico}" th:mce_href="@{/images/favicon.ico}" type="image/x-icon">

  <!-- CSS  -->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="plugins/bootstrap-4.0.0/css/bootstrap.min.css" th:href="@{/plugins/bootstrap-4.0.0/css/bootstrap.min.css}" type="text/css" rel="stylesheet"/>
  <link href="css/materialize.css" th:href="@{/css/materialize.css}" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="plugins/perfect-scrollbar/perfect-scrollbar.css" th:href="@{/plugins/perfect-scrollbar/perfect-scrollbar.css}" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" th:href="@{/css/style.css}" type="text/css" rel="stylesheet"/>

  <style>
    .input-field > label:not(.label-icon).active {
      line-height: 0rem;
    }
    .select-wrapper input.select-dropdown {
      font-size: 26px;
      height: 4.5rem;
    }
  </style>
</head>
<body>
  <header>
    <nav class="" role="navigation" style="background-color: #f4f6f9;">
      <div class="nav-wrapper">
        <ul class="right hide-on-med-and-down">
          <!-- 
          <li><a class="blue-text waves-effect dropdown-trigger" href="#!" data-target="dropdown1" style="vertical-align: top;"><span th:if="${session.user!=null}" th:text="${session.user.username}">admin</span><i class="material-icons right">arrow_drop_down</i></a></li>
           -->
          <li><a class="grey-text waves-effect dropdown-trigger" href="#!" data-target="dropdown1" style="vertical-align: top;"><span sec:authentication="name">admin</span><i class="material-icons right">arrow_drop_down</i></a></li>
          <ul id="dropdown1" class="dropdown-content">
            <li><a href="#modal3" class="waves-effect grey-text modal-trigger">修改密码</a></li>
            <li><a th:href="@{/company/logout}" class="waves-effect grey-text">退出登录</a></li>
          </ul>
        </ul>

        <a href="#" data-target="slide-out" class="sidenav-trigger"><i class="material-icons">menu</i></a>
      </div>
    </nav>
  </header>
  
  <div th:replace="common/aside_company :: aside"></div>

  <main class="" style="height: calc(100% - 48px); background-color: #f4f6f9;">
    <div class="row">
      <h6 style="margin: 0 0 0 15px;" id="page-title" active-menu="validate-menu">验证优惠券</h6>
    </div>

    <div class="white" style="margin: 0 15px; height: inherit;">
      <div class="row" style="width: 38rem;">
        <div class="col input-field">
          <select name="activityId">
            <option value="" disabled selected>权益</option>
            <option th:each="a : ${activities}" th:value="${a.id}"  th:text="${a.title}">权益1</option>
          </select>
          <span class="helper-text" data-error="wrong" data-success="right"></span>
        </div>
      </div>
      <div class="row" style="width: 38rem;">
        <div class="col input-field" style="float: left;">
          <input type="text" id="coupon" name="coupon" maxlength="12" style="font-size: 40px; font-weight: 700; height: 4.5rem;" >
          <label for="coupon" style="font-size: 26px;">优惠券验证码</label>
        </div>
        <div class="col input-field" style="float: left;">
          <input type="text" id="secret" name="secret" maxlength="12" style="font-size: 40px; font-weight: 700; height: 4.5rem;" >
          <label for="secret" style="font-size: 26px;">优惠券密码</label>
        </div>
      </div>
      <div class="row" style="width: 38rem;">
        <div class="col input-field" style="text-align: center;">
          <button class="waves-effect waves-light btn btn-large light-blue darken-1" onclick="validateSubmit();" style="margin: 5px; font-size: 20px;"><i class="material-icons left">bubble_chart</i>验证</button>
        </div>
      </div>
  	</div>
    <div class="row" style="margin: 0 15px; display: none;">
      <div class="col s8">
        <div id="table_body_div" style="max-height: 320px; position: relative;">
          <div>
	          <table>
	            <thead>
	              <tr>
	                <th width="50%" class="center">
	                  <label>
	                    <input type="checkbox" id="select_all" class="filled-in"/>
	                    <span style="top: 8px;"></span>
	                  </label>
	                </th>
	                <th width="50%">验证码</th>
	              </tr>
	            </thead>
	          </table>
	        </div>
	        <div>
	          <table class="highlight">
	            <thead>
	              <tr>
	                <th class="no-padding" width="50%"></th>
	                <th class="no-padding" width="50%"></th>
	              </tr>
	            </thead>
	            <tbody id="tbody">
	              <!-- <tr>
	                <td>
	                  <label>
	                    <input type="checkbox" checked="checked" />
	                    <span></span>
	                  </label>
	                </td>
	                <td>8888888888</td>
	              </tr> -->
	            </tbody>
	          </table>
	        </div>
        </div>
      </div>

    </div>
  </main>

  <!-- <footer class="white page-footer teal">
    <div class="footer-copyright">
      <div class="black-text container">
      Made by <a class="brown-text text-lighten-3" href="http://materializecss.com">Materialize</a>
      </div>
    </div>
  </footer> -->
  
  <div th:replace="common/update_pwd :: #modal3"></div>

  <!--  Scripts-->
  <script src="js/jquery-3.3.1.min.js" th:src="@{/js/jquery-3.3.1.min.js}"></script>
  <script src="js/materialize.js" th:src="@{/js/materialize.js}"></script>
  <script src="plugins/perfect-scrollbar/perfect-scrollbar.min.js" th:src="@{/plugins/perfect-scrollbar/perfect-scrollbar.min.js}"></script>
  <script src="plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js" th:src="@{/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js}"></script>
  <script src="plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js" th:src="@{/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js}" charset="UTF-8"></script>
  <script src="plugins/bootstrap-sweetalert/sweetalert.min.js" th:src="@{/plugins/bootstrap-sweetalert/sweetalert.min.js}"></script>
  <script src="js/common.js" th:src="@{/js/common.js}"></script>
  <script>
    $("#coupon").focus();

    var p = document.getElementById('table_body_div');

    function validateSubmit() {
    	var activityId =  $('select[name="activityId"]').val();
    	if(!activityId) {
    		swal("请选择权益!", {
          icon: "error",
          //timer: 2000,
        });
    		return;
    	}
    	var coupon_code = $('#coupon').val().replace(/ /g, '');
    	if(!coupon_code) {
    		swal("请输入优惠券验证码!", {
          icon: "error",
          //timer: 2000,
        });
    		return;
    	}
    	$.ajax({
    		type: "POST",
				url: "/kangchenjunga/api/v2/coupons/" + coupon_code + "/verify",
				data: "secretCode=" + $('#secret').val() + "&activityId=" + $('select[name="activityId"]').val(),
				success: function(data){
				  //alert( "Data Saved: " + msg );
				  if(data.verify.opResult == "success") {
					  var table_str = '';
            if(data.others != null && data.others.length > 0) {
              data.others.forEach(function(v) {
                table_str += '<tr>'
                         + '<td class="center">'
                         + '<label>'
                         + '<input type="checkbox" name="couponCode" class="filled-in" value="' + v.inputCouponCode + '" />'
                         +  '<span style="top: 8px;"></span>'
                         + '</label>'
                         + '</td>'
                         + '<td>' + v.inputCouponCode + '</td>'
                         + '</tr>';
              });
            }
					  $('#tbody').html(table_str);
					  swal({
	            title: coupon_code,
	            icon: "success",
	            text: "该优惠券验证码有效，并且可与下列优惠券同时使用",
	            content: {
	              element: p,
	            },
	            buttons: {
	              cancel: {
	                text: "取消",
	                value: false,
	                visible: true,
	                className: "waves-effect waves-light btn-flat",
	                closeModal: true,
	              },
	              confirm: {
	                text: "使用",
	                value: true,
	                className: "waves-effect waves-light"
	              }
	            },
	          }).then(function(willDelete) {
	        	  if (willDelete) {
	        		  //console.log($("input[name='couponCode']:checked")[0].value);
	        		  //console.log($("input[name='couponCode']:checked")[1].value);

	        		  var couponCodeCheckboxes = $("input[name='couponCode']:checked");
	        		  var couponCodeArr = '';
	        		  couponCodeArr += '["' + coupon_code + '"';
	        		  if(couponCodeCheckboxes.length > 0) {
	        			  for(var i = 0; i < couponCodeCheckboxes.length; i++) {
	        				  couponCodeArr += ', "' + couponCodeCheckboxes[i].value + '"';
	        			  }
	        		  }
	        		  couponCodeArr += ']';
	        		  console.log(couponCodeArr);
	        		  $.ajax({
       		        url: "/kangchenjunga/api/v2/coupons/services/redeem?&activityId=" + $('select[name="activityId"]').val() + "&remark=",
       		        data: couponCodeArr,
       		        contentType: "application/json;charset=utf-8",
       		        type: "POST",
       		        headers: {
       		          Accept: "application/json"
       		        },
       		        dataType: "json",
       		        success: function(data, textStatus) {
       		          console.log(data);
       		          if(data.length > 0 && data[0].opResult == 'success') {
       		        	  swal("使用成功!", {
       		              icon: "success",
       		              //timer: 2000,
       		            });
       		          } else {
       		        	  swal("使用失败!", {
                        icon: "error",
                        //timer: 2000,
                      });
       		          }
       		        },
       		        error: function() {
       		        	swal("使用失败!", {
                      icon: "error",
                      //timer: 2000,
                    });
       		        }
       		      });

	        		  $("#coupon").val("");
	        		  $("#secret").val("");
	        		  $("#coupon").focus();
        		  } else {
        			  $("#coupon").focus();
        		  }
        		});
				  } else {
					  swal({
              title: coupon_code,
              icon: "error",
              text: data.verify.opResultDetail
            })
				  }

				}
    	});

    }

    var inputDom = document.getElementById('coupon');
    var maxLen = 0;
    inputDom.oninput = function() {
        var value = this.value;
        var valueLen = value.length;
        var foucsNum = getCursortPosition(inputDom);
        if(valueLen > 0){
            var c = value.replace(/\s/g,  "");
            var Len = c.length;
            var List = c.split('');
            var initNum = 0;
            for(var i=1;i<Len;i++) {
                if(i%4 == 0) {　　//每四位分一组
                    List.splice(i+initNum,0,' ');　　//此处为使用空格分隔
                    initNum++
                }
            }
            this.value  = List.join('');

            if(maxLen < this.value.length) {
                if(foucsNum%5 == 0) {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum+1)
                    },0);
                }else {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum)
                    },0);
                }
            }else {
                if(foucsNum%5 == 0) {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum-1)
                    },0);
                }else {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum)
                    },0);
                }
            }
            maxLen = this.value.length;
        }
    }
    
    inputDom.onchange = function() {
        var value = this.value;
        var valueLen = value.length;
        var foucsNum = getCursortPosition(inputDom);
        if(valueLen > 0){
            var c = value.replace(/\s/g,  "");
            var Len = c.length;
            var List = c.split('');
            var initNum = 0;
            for(var i=1;i<Len;i++) {
                if(i%4 == 0) {　　//每四位分一组
                    List.splice(i+initNum,0,' ');　　//此处为使用空格分隔
                    initNum++
                }
            }
            this.value  = List.join('');

            if(maxLen < this.value.length) {
                if(foucsNum%5 == 0) {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum+1)
                    },0);
                }else {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum)
                    },0);
                }
            }else {
                if(foucsNum%5 == 0) {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum-1)
                    },0);
                }else {
                    setTimeout(function() {
                        setCaretPosition(inputDom,foucsNum)
                    },0);
                }
            }
            maxLen = this.value.length;
        }
    }

　   //控制光标移动时，需要使用定时器，避免出现光标控制失效的情况
    function getCursortPosition(ctrl) {        //获取光标的位置
        var CaretPos = 0;   // IE Support
        if (document.selection) {
            ctrl.focus();
            var Sel = document.selection.createRange();
            Sel.moveStart ('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
            CaretPos = ctrl.selectionStart;
        return (CaretPos);
    }

    function setCaretPosition(ctrl, pos) {        //设置光标的位置
        if(ctrl.setSelectionRange){
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        }
        else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }

  </script>

  </body>
</html>
